// import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';

// export interface IndexModelState {
//   name: string;
// }

// export interface IndexModelType {
//   namespace: 'index';
//   state: IndexModelState;
//   effects: {
//     query: Effect;
//   };
//   reducers: {
//     save: Reducer<IndexModelState>;
//     // 启用 immer 之后
//     // save: ImmerReducer<IndexModelState>;
//   };
//   subscriptions: { setup: Subscription };
// }

import { getTodos } from '@/pages/user/service';
const IndexModel = {
  // 设置命名空间
  namespace: 'user',
  // 管理数据
  state: {
    counter: 100,
    todos: [],
  },
  // 异步处理
  effects: {
    *getTodos({ payload }, { call, put }) {
      const data = yield call(getTodos);
      yield put({
        type: 'setTodos',
        payload: data,
      });
    },
  },
  // 同步处理
  reducers: {
    // save(state, action) {
    //   return {
    //     ...state,
    //     ...action.payload,
    //   };
    // },
    // increment(state, { payload }) {
    //   // console.log(1);
    //   return {
    //     ...state,
    //     counter: (state.counter += payload),
    //   };
    // },
    setTodos(state, { payload }) {
      state.todos = payload;
    },
    increment(state, { payload }) {
      state.counter += payload;
    },
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },
  // 订阅消息，可以设置进入某个路由页面的时候自动触发操作
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/user') {
          dispatch({
            type: 'getTodos',
          });
        }
      });
    },
  },
};

export default IndexModel;
